
# -*- coding: utf-8 -*-

from django.db import models
from django.utils.encoding import force_unicode
from django.contrib.auth.models import User
from Grupos.models import Grupo
from Plugins.ContentTypeRestrictedFileField import ContentTypeRestrictedFileField
import unicodedata

class Link(models.Model):
	titulo = models.CharField(max_length=200, verbose_name="Titulo")
	url = models.CharField(max_length=200, verbose_name="URL")

	class Meta:
		db_table = 'links'
		ordering = ['titulo']
		verbose_name = "Link"

	def __unicode__(self):
		return force_unicode(self.titulo)

class Documento(models.Model):
	titulo = models.CharField(max_length=200, verbose_name="Titulo")
	documento = ContentTypeRestrictedFileField(max_length=200, upload_to='documentos', verbose_name='Documento',
											   content_types=['application/pdf', 'application/zip'],
											   max_upload_size=34971520)

	class Meta:
		db_table = 'documentos'
		ordering = ['titulo']
		verbose_name = "Documento"

	def __unicode__(self):
		return force_unicode(self.titulo)

	def save(self, *args, **kwargs):
		for field in self._meta.fields:
			if field.name == 'documento':
				field.upload_to = 'documentos/%s' % unicodedata.normalize('NFKD', self.titulo).encode('ascii','ignore').replace(" ", "")
				break
		super(Documento, self).save(args, kwargs)

	def delete(self, *args, **kwargs):
		storage, path = self.documento.storage, self.documento.path
		super(Documento, self).delete(*args, **kwargs)
		storage.delete(path)

class Proyecto(models.Model):
	nombre = models.CharField(max_length=200, verbose_name="Nombre del Proyecto", unique=True, blank=False, null=False)
	imagen = models.ImageField(upload_to='proyectos', max_length=200, blank=True, null=False, default="default.png")
	creador = models.ForeignKey(User, related_name="proyectos", verbose_name="Creador", null=False, blank=False)
	grupos = models.ManyToManyField(Grupo, related_name="proyectos", verbose_name="Grupos", null=True, blank=True)
	links = models.ManyToManyField(Link, related_name="proylinks", verbose_name="Links")
	documentos = models.ManyToManyField(Documento, related_name="proydocs", verbose_name="Documentos")

	grupos.help_text = ''
	links.help_text = ''
	documentos.help_text = ''

	class Meta:
		db_table = 'proyectos'
		ordering = ['nombre']
		verbose_name = "Proyecto"

	def __unicode__(self):
		return force_unicode(self.nombre)

	def save(self, *args, **kwargs):
		for field in self._meta.fields:
			if field.name == 'imagen':
				field.upload_to = 'proyectos/%s' % unicodedata.normalize('NFKD', self.nombre).encode('ascii','ignore').replace(" ", "")
				break
		super(Proyecto, self).save(args, kwargs)

	def delete(self, *args, **kwargs):
		storage, path = self.imagen.storage, self.imagen.path
		super(Proyecto, self).delete(*args, **kwargs)
		if not path.endswith('default.png'):
			storage.delete(path)
